package com.sunny.ynhz.ui;

import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.BottomSheetDialog;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.FutureTarget;
import com.bumptech.glide.request.target.Target;
import com.sunny.ynhz.R;
import com.sunny.ynhz.adapter.MyViewPagerAdapter;
import com.sunny.ynhz.ui.base.BaseActivity;
import com.sunny.ynhz.utils.ToastUtils;


import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ExecutionException;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by luao on 2017/5/18.
 */

public class ImageActivity extends BaseActivity {
    @BindView(R.id.vp)
    ViewPager vp;
    @BindView(R.id.tv_number)
    TextView tv_number;
    private static String imagePath;
    private File absoluteFile;
    private String imageUrl;
    private View item_sava_img;
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            ToastUtils.SingleToastUtil(ImageActivity.this, "保存成功");
            bottomSheetDialog.dismiss();

        }
    };
    private BottomSheetDialog bottomSheetDialog;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_imageview);
        bottomSheetDialog = new BottomSheetDialog(this);
        item_sava_img = LayoutInflater.from(this).inflate(R.layout.item_sava_img, null);

        bottomSheetDialog.setContentView(item_sava_img);
        ButterKnife.bind(this);
        String fileName;
        if (Build.BRAND.equals("Xiaomi")) { // 小米手机
            fileName = Environment.getExternalStorageDirectory().getPath() + "/DCIM/Camera/";
        } else {
            fileName = Environment.getExternalStorageDirectory().getPath() + "/DCIM/";
        }
        absoluteFile = new File(fileName);
        Intent intent = getIntent();
        imageUrl = intent.getStringExtra("pic_path");
        String path = intent.getStringExtra("path");
        String[] split = imageUrl.split(".,,.");
        List<String> strings = Arrays.asList(split);
        MyViewPagerAdapter myViewPagerAdapter = new MyViewPagerAdapter(this, strings);
        vp.setAdapter(myViewPagerAdapter);
        vp.setOffscreenPageLimit(strings.size());
        int i = strings.indexOf(path);
        vp.setCurrentItem(i);
        tv_number.setText((i + 1) + "/" + strings.size());
        vp.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                String s = (position + 1) + "/" + split.length;
                tv_number.setText(s);


            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    public void showDigo(String imageUrl) {
        bottomSheetDialog.show();
        item_sava_img.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                downImgAndSavaImg(imageUrl);
            }
        });
    }


    public void downImgAndSavaImg(String imageUrl) {
        new Thread() {
            @Override
            public void run() {
                FutureTarget<File> fileFutureTarget = Glide.with(ImageActivity.this).load(imageUrl).downloadOnly(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL);
                String fileName = "tempName";
                File appDir = new File(absoluteFile, fileName);
                if (!appDir.exists())
                    appDir.mkdirs();
                fileName = System.currentTimeMillis() + ".png";
                File newFile = new File(appDir, fileName);
                try {
                    copyFile(fileFutureTarget.get(), newFile);
                    sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(new File(newFile.getPath()))));
                    handler.sendEmptyMessage(0);

                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (ExecutionException e) {
                    e.printStackTrace();
                }
            }
        }.start();

    }

    public void copyFile(File oldPath, File newPath) {
        try {
            int byteread = 0;
            if (oldPath.exists()) { //文件存在时
                InputStream inStream = new FileInputStream(oldPath); //读入原文件
                FileOutputStream fs = new FileOutputStream(newPath);
                byte[] buffer = new byte[1444];
                while ((byteread = inStream.read(buffer)) != -1) {
                    fs.write(buffer, 0, byteread);
                }
                inStream.close();
            }
        } catch (Exception e) {
            e.printStackTrace();

        }

    }

}


